package com.micro.business.admin.config.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * redis工具类
 *
 * @author 高仕立
 * @date 2017/11/30 14:48
 */
@Component
public class RedisTemplateManager {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(RedisTemplateManager.class);
    
    @Autowired
    private RedisTemplate redisTemplate;
    
    /**
     * 设置对象
     *
     * @param key key
     * @param value value值
     * @param <T> 返回值泛型
     * @return 正确的值：<T>
     * 错误的值：null
     */
    public <T> ValueOperations<String, T> setObject(final String key, final T value) {
        LOGGER.info("******RedisManager（setObject）******key:{},obj:{}", key, value);
        final ValueOperations<String, T> operation = redisTemplate.opsForValue();
        try {
            operation.set(key, value);
        } catch (final Exception e) {
            LOGGER.error(key + "," + value.toString() + "_" + e.getMessage(), e);
        }
        return operation;
    }
    
    /**
     * 设置对象-过期自动删除（单位秒）
     *
     * @param key redis 键
     * @param value redis 值
     * @param seconds 过期时长
     * @param <T> 对象类型
     * @return
     */
    public <T> ValueOperations<String, T> setObjectWithTimeout(final String key, final T value, final Long seconds) {
        final ValueOperations<String, T> operation = redisTemplate.opsForValue();
        try {
            operation.set(key, value, seconds, TimeUnit.SECONDS);
        } catch (final Exception e) {
            e.printStackTrace();
            LOGGER.error(key + "," + value.toString() + "_" + e.getMessage(), e);
        }
        return operation;
    }

    /**
     * 给指定key单独设置超时时间
     *
     * @param key
     * @param expire
     * @return boolean
     * @author 高仕立
     * @since 2019/8/2 09:15
     */
    public boolean expire(String key, long expire) {
        return redisTemplate.expire(key, expire, TimeUnit.SECONDS);
    }
    
    /**
     * 获取对象
     *
     * @param key 键
     * @return 正确的值：Object值对象<br>
     * 错误的值：null
     */
    public Object getObject(final String key) {
        LOGGER.info("******RedisManager（getObject）******key:{}", key);
        final ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        if (valueOperations == null || !redisTemplate.hasKey(key)) {
            LOGGER.info("******RedisManager（getObject）******没有找到");
            return null;
        }
        Object object = null;
        try {
            object = valueOperations.get(key);
            LOGGER.info("******RedisManager（getObject）******object:{}", object);
        } catch (final Exception e) {
            LOGGER.error(key + "_" + e.getMessage(), e);
        }
        return object;
    }
    
    /**
     * 从redis缓存中获取string值
     *
     * @param key
     * @return
     */
    @SuppressWarnings("unchecked")
    public String getString(final String key) {
        String value = "";
        final ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        if (valueOperations != null && redisTemplate.hasKey(key)) {
            final Object object = valueOperations.get(key);
            if (null != object) {
                LOGGER.info("--getString--object not empty");
                value = object.toString();
            } else {
                LOGGER.info("--getString--object empty");
            }
        }
        return value;
    }
    
    /**
     * 设置对象及失效时间
     *
     * @param key key
     * @param value value值
     * @param <T> 返回值泛型
     * @param time 秒值
     * @return 正确的值：<T> 错误的值：null
     */
    @SuppressWarnings("unchecked")
    public <T> ValueOperations<String, T> setObject(final String key, final T value, final long time) {
        final ValueOperations<String, T> operation = redisTemplate.opsForValue();
        operation.set(key, value, time, TimeUnit.SECONDS);
        return operation;
    }

    /**
     * 从缓存中删除值
     *
     * @param key
     * @return
     * @author wdx
     * @date 2017年12月11日
     */
    @SuppressWarnings("unchecked")
    public boolean delete(final String key) {
        return redisTemplate.delete(key);
    }

    /**
     * 自增操作
     *
     * @param key
     * @param delta 自增步长
     * @return java.lang.Long
     * @author 高仕立
     * @since 2019/8/2 09:02
     */
    @SuppressWarnings("unchecked")
    public Long increment(String key, long delta){
       return redisTemplate.opsForValue().increment(key,delta);
    }
}

